package cn.hznc.controller.service.toolfork;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
//import cn.hznc.configuration.MinioHelper;
import cn.hznc.configuration.MinioHelper;
import cn.hznc.constant.ToolParamEnum;
import cn.hznc.controller.uploadfilestrategy.RemoveFileContext;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.common.QueryCondition;
import cn.hznc.domain.request.toolfork.*;
import cn.hznc.domain.response.PageResult;
import cn.hznc.dto.ToolForkInfoExport;
import cn.hznc.dto.ToolForkInfoImport;
import cn.hznc.dto.ToolForkInfoPriceImport;
import cn.hznc.exception.ToolManageEx;
import cn.hznc.exception.ToolManageException;
import cn.hznc.mapper.ToolConnectMapper;
import cn.hznc.mapper.ToolForkInfoMapper;
import cn.hznc.mapper.ToolLifeMapper;
import cn.hznc.mapper.TypeItemMapper;
import cn.hznc.repository.*;
import cn.hznc.utils.CommonUtil;
import cn.hznc.vo.*;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.hznc.constant.ToolConstant.NONE_TYPE;

/**
 * 刀具浏览服务
 *
 * @author xiahuanyu
 * @date 2023/3/3
 */
@Service
public class ToolForkService {

    @Resource
    private ToolForkRespository toolForkRespository;

    @Resource
    private AssemblyToolConnectRespository assemblyToolConnectRespository;

    @Resource
    private TypeItemMapper typeItemMapper;

    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;

    @Resource
    private ToolLifeMapper toolLifeMapper;

    @Resource
    private TypeItemRepository typeItemRepository;

    @Autowired
    private MinioHelper minioHelper;

    @Autowired
    private MinioProp minioProp;

    @Resource
    private AssemblyToolRespository assemblyToolRespository;

    @Resource
    private ToolPartRespository toolPartRespository;

    @Resource
    private ToolLifeRepository toolLifeRepository;

    @Resource
    private ToolConnectMapper toolConnectMapper;

    private static final String IMAGE = "image";

    private static final String TWO_DIMENSIONAL_MODEL = "twoDimensionalModel";

    private static final String THREE_DIMENSIONAL_MODEL = "threeDimensionalModel";


    /**
     * 工具参数
     */
    private static final HashMap<String, String> toolParamMap = new HashMap<>();

    private static final HashMap<String, String> toolTypeFirstMap = new HashMap<>();

    private static final HashMap<String, String> toolTypeSecMap = new HashMap<>();

    private static final ArrayList removalList = new ArrayList();

    static {
        Arrays.stream(ToolParamEnum.values()).forEach(
                toolParamEnum -> toolParamMap.put(toolParamEnum.getNameEn(), toolParamEnum.getName())
        );
        toolTypeFirstMap.put("刀具", "A001B001");
        toolTypeFirstMap.put("工具系统", "A001B002");
        toolTypeFirstMap.put("刀片", "A001B003");
        toolTypeSecMap.put("车削刀具", "A001B001C001");
        toolTypeSecMap.put("铣削刀具", "A001B001C002");
        toolTypeSecMap.put("孔加工刀具", "A001B001C003");
        removalList.add("PictureUri");
        removalList.add("SizeChartUri");
        removalList.add("guid");
        removalList.add("DetailedModelUri");
        removalList.add("BasicModelUri");
        removalList.add("simplePartModelUri");
        removalList.add("partModelUri");
        removalList.add("DetailedModelUri");

    }

    /**
     * 处理后的toolfork对象
     *
     * @param queryToolInfoReq queryToolInfoReq
     * @return 处理后的toolfork对象
     */
    public PageResult<ToolForkInfoEntity> query(QueryToolInfoReq queryToolInfoReq) {
//        List<AssemblyToolConnectEntity> assemblyToolConnectEntityList = qryConnectData(queryToolInfoReq.getConnectConditions());
//        // 设置刀具关联的类型查询条件
//        List<String> typeList = buildTypeList(assemblyToolConnectEntityList);
//        queryToolInfoReq.setTypeList(typeList);
        PageHelper.startPage(queryToolInfoReq.getPageNum(), queryToolInfoReq.getPageSize());
        // 字段白名单----待做
        List<QueryCondition> conditions = queryToolInfoReq.getQueryCondition().stream().
                filter(queryCondition -> StringUtils.isNotEmpty(queryCondition.getCondition())).collect(Collectors.toList());
        queryToolInfoReq.setQueryCondition(conditions);
        List<ToolForkInfoEntity> toolForkInfoEntityList = toolForkRespository.queryByCondition(queryToolInfoReq, 0, "");
        if (CollectionUtil.isEmpty(toolForkInfoEntityList)) {
            return new PageResult<>(null, 0L);
        }
        PageInfo<ToolForkInfoEntity> result = new PageInfo<>(toolForkInfoEntityList);
        List<ToolForkInfoEntity> toolForkInfoSimpleVos = result.getList().stream().map(this::setQryIndex).collect(Collectors.toList());
        return new PageResult<>(toolForkInfoSimpleVos, result.getTotal());
    }

    public List<ToolForkInfoEntity> queryReload(QueryToolInfoReq queryToolInfoReq) {
        //PageHelper.startPage(queryToolInfoReq.getPageNum(),queryToolInfoReq.getPageSize());
        // 字段白名单----待做
        List<QueryCondition> conditions = queryToolInfoReq.getQueryCondition().stream().
                filter(queryCondition -> StringUtils.isNotEmpty(queryCondition.getCondition())).collect(Collectors.toList());
        queryToolInfoReq.setQueryCondition(conditions);
        List<ToolForkInfoEntity> toolForkInfoEntityList = toolForkRespository.queryByConditionReload(queryToolInfoReq);
        if (CollectionUtil.isEmpty(toolForkInfoEntityList)) {
            return new ArrayList<>();
        }
        //PageInfo<ToolForkInfoEntity> result = new PageInfo<>(toolForkInfoEntityList);
        //List<ToolForkInfoEntity> toolForkInfoSimpleVos = result.getList().stream().map(this::setQryIndex).collect(Collectors.toList());
        return toolForkInfoEntityList;
    }

    /**
     * 14位ccws匹配14位
     *
     * @param queryToolInfoReq
     * @param flag
     * @param match1
     * @param match2
     * @return
     */
    public List<ToolForkInfoEntity> queryCCWSReload1(QueryToolInfoReq queryToolInfoReq, Integer flag, String match1, String match2, String match3) {
        //PageHelper.startPage(queryToolInfoReq.getPageNum(),queryToolInfoReq.getPageSize());
        // 字段白名单----待做
        List<QueryCondition> conditions = queryToolInfoReq.getQueryCondition().stream().
                filter(queryCondition -> StringUtils.isNotEmpty(queryCondition.getCondition())).collect(Collectors.toList());
        queryToolInfoReq.setQueryCondition(conditions);
        List<ToolForkInfoEntity> toolForkInfoEntityList = toolForkRespository.queryCCWSReload1(queryToolInfoReq, flag
                , match1, match2, match3);
        if (CollectionUtil.isEmpty(toolForkInfoEntityList)) {
            return new ArrayList<>();
        }
        //PageInfo<ToolForkInfoEntity> result = new PageInfo<>(toolForkInfoEntityList);
        //List<ToolForkInfoEntity> toolForkInfoSimpleVos = result.getList().stream().map(this::setQryIndex).collect(Collectors.toList());
        return toolForkInfoEntityList;
    }

    /**
     * 14位ccws匹配28位
     *
     * @param queryToolInfoReq
     * @param flag
     * @param match1
     * @param match2
     * @return
     */
    public List<ToolForkInfoEntity> queryCCWSReload2(QueryToolInfoReq queryToolInfoReq, Integer flag, String match1, String match2) {
        //PageHelper.startPage(queryToolInfoReq.getPageNum(),queryToolInfoReq.getPageSize());
        // 字段白名单----待做
        List<QueryCondition> conditions = queryToolInfoReq.getQueryCondition().stream().
                filter(queryCondition -> StringUtils.isNotEmpty(queryCondition.getCondition())).collect(Collectors.toList());
        queryToolInfoReq.setQueryCondition(conditions);
        List<ToolForkInfoEntity> toolForkInfoEntityList = toolForkRespository.queryByConditionReload(queryToolInfoReq);
        if (CollectionUtil.isEmpty(toolForkInfoEntityList)) {
            return new ArrayList<>();
        }
        //PageInfo<ToolForkInfoEntity> result = new PageInfo<>(toolForkInfoEntityList);
        //List<ToolForkInfoEntity> toolForkInfoSimpleVos = result.getList().stream().map(this::setQryIndex).collect(Collectors.toList());
        return toolForkInfoEntityList;
    }

    private ToolForkInfoEntity setQryIndex(ToolForkInfoEntity toolForkInfoEntity) {
        String baseUrl = minioProp.getBaseUrl() + minioProp.getBucketName() + "/";
        String httpsBaseUrl = minioProp.getHttpsBaseUrl() + minioProp.getBucketName() + "/";
        if (StringUtils.isNotEmpty(toolForkInfoEntity.getImage())) {
            toolForkInfoEntity.setImage(baseUrl + toolForkInfoEntity.getImage());
        }
        if (StringUtils.isNotEmpty(toolForkInfoEntity.getTwoDimensionalModel())) {
            toolForkInfoEntity.setTwoDimensionalModel(baseUrl + toolForkInfoEntity.getTwoDimensionalModel());
        }
        if (StringUtils.isNotEmpty(toolForkInfoEntity.getThreeDimensionalModel())) {
            toolForkInfoEntity.setThreeDimensionalModel(baseUrl + toolForkInfoEntity.getThreeDimensionalModel());
        }
        if (StringUtils.isNotEmpty(toolForkInfoEntity.getThreeDimensionalModelStl())) {
            toolForkInfoEntity.setThreeDimensionalModelStl(httpsBaseUrl + toolForkInfoEntity.getThreeDimensionalModelStl());
        }
        toolForkInfoEntity.setQryIndex(typeItemRepository.getIndexByType(toolForkInfoEntity.getType()));
        return toolForkInfoEntity;
    }

    private List<String> buildTypeList(List<AssemblyToolConnectEntity> assemblyToolConnectEntityList) {
        if (CollectionUtil.isEmpty(assemblyToolConnectEntityList)) {
            return new ArrayList<String>();
        }
        List<String> forkTypeList = assemblyToolConnectEntityList.stream().map(AssemblyToolConnectEntity::getForkType).distinct().collect(Collectors.toList());
        List<String> cutterTypeList = assemblyToolConnectEntityList.stream().map(AssemblyToolConnectEntity::getCutterType).distinct().collect(Collectors.toList());
        List<String> auxiliaryToolTypeList = assemblyToolConnectEntityList.stream().map(AssemblyToolConnectEntity::getAuxiliaryToolType).filter(NONE_TYPE::equals).distinct().collect(Collectors.toList());
        List<String> typeList = new ArrayList<>();
        typeList.addAll(forkTypeList);
        typeList.addAll(cutterTypeList);
        typeList.addAll(auxiliaryToolTypeList);
        return typeList;
    }

    private List<AssemblyToolConnectEntity> qryConnectData(List<ConnectCondition> connectConditions) {
        List<AssemblyToolConnectEntity> assemblyToolConnectEntityList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(connectConditions)) {
            // 查询总成刀具关联的类型
            assemblyToolConnectEntityList = assemblyToolConnectRespository.queryConnectData(connectConditions);
        }
        return assemblyToolConnectEntityList;
    }

    /**
     * 删除刀具库中的组件
     *
     * @return boolean
     */
    public boolean delete(List<Integer> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return Boolean.FALSE;
        }
        toolForkRespository.deleteToolFork(ids);
        return Boolean.TRUE;
    }

    /**
     * 编辑刀具库中的组件
     *
     * @param entity entity
     * @return boolean
     */
    public boolean edit(ToolForkInfoEntity entity) {
        if (ObjectUtils.isEmpty(entity.getId())) {
            return Boolean.FALSE;
        }
        entity.setParameters(null);
        toolForkInfoMapper.updateById(entity);
        return Boolean.TRUE;
    }

    /**
     * 填充参数
     *
     * @param entity       entity
     * @param targetEntity targetEntity
     * @return ToolForkInfoEntity
     */
    private ToolForkInfoEntity buildEntity(ToolForkInfoEntity entity, ToolForkInfoEntity targetEntity) {
        targetEntity.setImage(entity.getImage());
        targetEntity.setType(entity.getType());
        targetEntity.setDc(entity.getDc());
        targetEntity.setGrdmfg(entity.getGrdmfg());
        targetEntity.setPartno(entity.getPartno());
        targetEntity.setOal(entity.getOal());
        targetEntity.setHand(entity.getHand());
        targetEntity.setCcws(entity.getCcws());
        targetEntity.setInsl(entity.getInsl());
        targetEntity.setDescription(entity.getDescription());
        // 处理其它参数
//        String parameters = targetEntity.getParameters();
//        JSONObject paramJson = buildParameter(entity, parameters);
//        targetEntity.setParameters(paramJson.toString());
        return targetEntity;
    }

    private JSONObject buildParameter(ToolForkInfoEntity entity, String parameters) {
        JSONObject paramJson = new JSONObject();
        if (!StringUtils.isEmpty(parameters)) {
            paramJson = JSONObject.parseObject(parameters);
        }
        paramJson.put(ToolParamEnum.DC.getNameEn(), CommonUtil.setSecondScale(entity.getDc()));
        paramJson.put(ToolParamEnum.GRDMFG.getNameEn(), entity.getGrdmfg());
        paramJson.put(ToolParamEnum.PARTNO.getNameEn(), entity.getPartno());
        paramJson.put(ToolParamEnum.OAL.getNameEn(), CommonUtil.setSecondScale(entity.getOal()));
        paramJson.put(ToolParamEnum.HAND.getNameEn(), entity.getHand());
        paramJson.put(ToolParamEnum.CCMS.getNameEn(), entity.getCcws());
        paramJson.put(ToolParamEnum.INSL.getNameEn(), CommonUtil.setSecondScale(entity.getInsl()));
        paramJson.put(ToolParamEnum.DESCRIPTION.getNameEn(), entity.getDescription());
        return paramJson;
    }

    /**
     * 新增刀具库中的组件
     *
     * @param entity entity
     * @return boolean
     */
    public boolean add(ToolForkInfoEntity entity) throws ToolManageException {
        QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
        //wrapper.eq("idnr", entity.getIdnr());
        wrapper.eq("partno", entity.getPartno());
        List<ToolForkInfoEntity> toolForkInfoEntity = toolForkInfoMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(toolForkInfoEntity)) {
            throw new ToolManageException(ToolManageEx.TOOL_IDNR_PARTNO_EXIST.getCode(), ToolManageEx.TOOL_IDNR_PARTNO_EXIST.getMsg());
        }
        toolForkInfoMapper.insert(entity);
        return Boolean.TRUE;
    }

    private void fillAddInfo(ToolForkInfoEntity entity, ToolForkInfoEntity targetEntity) {
        targetEntity.setIdnr(entity.getIdnr());
        targetEntity.setThreeDimensionalModel(entity.getThreeDimensionalModel());
        targetEntity.setTwoDimensionalModel(entity.getTwoDimensionalModel());
        targetEntity.setCreateTime(new Date());
    }

    /**
     * 返回目录
     *
     * @param queryIndexReq queryIndexReq
     * @return 目录
     */
    public List<ToolItemVo> queryToolForkIndex(QueryIndexReq queryIndexReq) {
        List<TypeItemEntity> typeItemEntities = toolForkRespository.queryTypeByIndex(queryIndexReq);
        List<ToolItemVo> toolItemVos = new ArrayList<>();
        for (TypeItemEntity entity : typeItemEntities) {
            List<Map<String, Object>> params = new ArrayList<>();
            ToolItemVo toolItemVo = new ToolItemVo();
            BeanUtils.copyProperties(entity, toolItemVo);
            if (StringUtils.isBlank(entity.getParams())) {
                String recursionTreeParams = recursionTreeParams(entity.getParentId() , entity.getParams());
                entity.setParams(recursionTreeParams);
            }
            String[] split = entity.getParams().split(",");
            for (String s : split) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("name", s);
                paramMap.put("value", "");
                params.add(paramMap);
            }
            //为空使用父级的params
            toolItemVo.setParamList(params);
            if(StringUtils.isNotBlank(entity.getSearchParams())){
                toolItemVo.setSearchParams(JSONArray.parseArray(entity.getSearchParams() , SearchParamsVo.class));
            }
            toolItemVos.add(toolItemVo);
        }
        return toolItemVos;
    }

    private String recursionTreeParams(Integer pid , String resultParams) {
        if(StringUtils.isNotBlank(resultParams) || ObjectUtil.isNull(pid)){
            return resultParams;
        }
        QueryWrapper<TypeItemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id" , pid);
        TypeItemEntity typeItemEntity = typeItemMapper.selectOne(wrapper);
        return recursionTreeParams(typeItemEntity.getParentId() , typeItemEntity.getParams());
    }

    public boolean importToolForkInfo(List<ToolForkInfoImport> toolForkInfoImportList) throws ToolManageException {
        if (CollectionUtil.isEmpty(toolForkInfoImportList)) {
            return Boolean.TRUE;
        }
        // 校验参数合法性
        List<String> typeNameList = toolForkInfoImportList.stream().map(ToolForkInfoImport::getTypeName).distinct().collect(Collectors.toList());
        LambdaQueryWrapper<TypeItemEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TypeItemEntity::getTypeName, typeNameList);
        List<TypeItemEntity> typeItemEntityList = typeItemMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(typeItemEntityList)) {
            throw new ToolManageException(ToolManageEx.TOOL_TYPE_NO_EXIST.getCode(), ToolManageEx.TOOL_TYPE_NO_EXIST.getMsg());
        }
        // 构造插入数据
        List<ToolForkInfoEntity> insertList = buildImportData(toolForkInfoImportList, typeItemEntityList);
        // 数据持久化
        toolForkInfoMapper.insertBatchSomeColumn(insertList);
        return Boolean.TRUE;
    }

    private List<ToolForkInfoEntity> buildImportData(List<ToolForkInfoImport> toolForkInfoImportList, List<TypeItemEntity> typeItemEntityList) throws ToolManageException {
        Map<String, String> typeMap = typeItemEntityList.stream().collect(Collectors.toMap(TypeItemEntity::getTypeName, TypeItemEntity::getType));
        List<ToolForkInfoEntity> insertList = new ArrayList<>();
        for (ToolForkInfoImport toolForkInfoImport : toolForkInfoImportList) {
            ToolForkInfoEntity toolForkInfoEntity = new ToolForkInfoEntity();
            if (typeMap.containsKey(toolForkInfoImport.getTypeName())) {
                toolForkInfoEntity.setType(typeMap.get(toolForkInfoImport.getTypeName()));
            } else {
                throw new ToolManageException(ToolManageEx.TOOL_TYPE_NO_EXIST.getCode(), ToolManageEx.TOOL_TYPE_NO_EXIST.getMsg());
            }
            BeanUtil.copyProperties(toolForkInfoImport, toolForkInfoEntity);
            // 模型参数处理
            JSONObject paramJson = buildParameter(toolForkInfoEntity, "");
            toolForkInfoEntity.setParameters(paramJson.toString());
            insertList.add(toolForkInfoEntity);
        }
        return insertList;
    }

    public void exportToolForkInfo(HttpServletResponse response, Integer toolForkInfoId) throws IOException {
        //设置excel文件的mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        ToolForkInfoEntity toolForkInfoEntity = toolForkRespository.queryById(toolForkInfoId);
        List<ToolForkInfoExport> resultList = getParameters(toolForkInfoEntity);
        String fileName = toolForkInfoEntity.getIdnr();
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ToolForkInfoExport.class).sheet("工件参数").doWrite(resultList);
    }

    private List<ToolForkInfoExport> getParameters(ToolForkInfoEntity toolForkInfoEntity) {
        List<ToolForkInfoExport> resultList = new ArrayList<>();
        JSONArray jsonArray = JSONObject.parseArray(toolForkInfoEntity.getParameters());
        if (ObjectUtil.isNotNull(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                ToolForkInfoExport toolForkInfoExport = new ToolForkInfoExport();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                toolForkInfoExport.setValue((String) jsonObject.get("value"));
                toolForkInfoExport.setNameEn(jsonObject.getString("nameEn"));
                toolForkInfoExport.setName(toolParamMap.getOrDefault(jsonObject.getString("nameEn"), ""));
                resultList.add(toolForkInfoExport);
            }
        }
        return resultList;
    }

    public void editToolForkParams(ToolForkParamReq toolForkParamReq) {
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectById(toolForkParamReq.getId());
        toolForkInfoEntity.setParameters(JSON.toJSONString(toolForkParamReq.getParams()));
        //持久化
        toolForkInfoMapper.updateById(toolForkInfoEntity);
    }

    public List<ToolParam> qryToolForkInfoById(Integer id) {
        String parameters = toolForkRespository.qryToolForkInfoById(id);
        List<ToolParam> toolParams = new ArrayList<>();
        JSONArray jsonArray = JSONObject.parseArray(parameters);
        buildToolParams(toolParams, jsonArray);
        //过滤参数
        if(CollectionUtil.isNotEmpty(toolParams)){
            toolParams = toolParams.stream().filter(toolParam -> !removalList.contains(toolParam.getNameEn())).collect(Collectors.toList());
        }
        return toolParams;
    }

    private void buildToolParams(List<ToolParam> toolParams, JSONArray jsonArray) {
        if (ObjectUtil.isNotNull(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                ToolParam toolParam = new ToolParam();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                toolParam.setValue(jsonObject.get("value"));
                toolParam.setNameEn(jsonObject.getString("nameEn"));
                toolParam.setName(toolParamMap.getOrDefault(jsonObject.getString("nameEn"), ""));
                toolParams.add(toolParam);
            }
        }
    }


    public Map<String, Object> uploadFile(MultipartFile image, MultipartFile twoDimensionalModel, MultipartFile threeDimensionalModel, MultipartFile threeDimensionalModelStl, String idnr, String partno) {
        QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("idnr", idnr);
        wrapper.eq("partno", partno);
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(toolForkInfoEntity)) {
            toolForkInfoEntity = new ToolForkInfoEntity();
        }
        String filename = "";
        Map<String, Object> filenameMap = new HashMap<>();
        //图片
        if (!ObjectUtil.isNull(image)) {
            filename = idnr + partno + IMAGE;

//            Context context = new Context();
//            context.uploadByStrategy("1" , image , filename);
            minioHelper.uploadFile(image, filename);
            filenameMap.put("image", filename + "." +getFilenameSuffix(image.getOriginalFilename()));
            toolForkInfoEntity.setImage(filename);
        }
        //二维图片
        if (!ObjectUtil.isNull(twoDimensionalModel) &&!twoDimensionalModel.isEmpty()) {
            filename = idnr + partno + TWO_DIMENSIONAL_MODEL;

//            Context context = new Context();
//            context.uploadByStrategy("1" , twoDimensionalModel , filename);
            minioHelper.uploadFile(twoDimensionalModel, filename);
            filenameMap.put("twoDimensionalModel", filename+ "." +getFilenameSuffix(image.getOriginalFilename()));
            toolForkInfoEntity.setTwoDimensionalModel(filename);
        }
        //三维图片
        if (!ObjectUtil.isNull(threeDimensionalModel) &&!threeDimensionalModel.isEmpty()) {
            filename = idnr + partno + THREE_DIMENSIONAL_MODEL;

//            Context context = new Context();
//            context.uploadByStrategy("1" , threeDimensionalModel , filename);
            minioHelper.uploadFile(threeDimensionalModel, filename);
            filenameMap.put("threeDimensionalModel", filename + "." +getFilenameSuffix(image.getOriginalFilename()));
            toolForkInfoEntity.setThreeDimensionalModel(filename);
        }
        //三维图片stl
        if (!ObjectUtil.isNull(threeDimensionalModelStl) &&!threeDimensionalModelStl.isEmpty() ) {
            filename = idnr + partno + THREE_DIMENSIONAL_MODEL;

//            Context context = new Context();
//            context.uploadByStrategy("1" , threeDimensionalModelStl , filename);
            minioHelper.uploadFile(threeDimensionalModelStl, filename);
            filenameMap.put("threeDimensionalModelStl", filename+ "." +getFilenameSuffix(image.getOriginalFilename()));
            toolForkInfoEntity.setThreeDimensionalModelStl(filename);
        }
        if (ObjectUtil.isNotNull(toolForkInfoEntity.getId())) {
            //表中存在记录则修改实体类图片地址
            toolForkInfoMapper.updateById(toolForkInfoEntity);
        }
        return filenameMap;
    }

    private String getFilenameSuffix(String filename){
        if(StringUtils.isNotBlank(filename)){
            String[] split = filename.split("\\.");
            return split[split.length-1];
        }
        return "";
    }

    public Map<String, Object> uploadFileUrl(MultipartFile image, MultipartFile twoDimensionalModel, MultipartFile threeDimensionalModel, MultipartFile threeDimensionalModelStl, String idnr, String partno) {
        QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("idnr", idnr);
        wrapper.eq("partno", partno);
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(toolForkInfoEntity)) {
            toolForkInfoEntity = new ToolForkInfoEntity();
        }
        String filename = "";
        Map<String, Object> filenameMap = new HashMap<>();
        //图片
        if (!ObjectUtil.isNull(image)) {
            filename = idnr + partno + IMAGE + ".jpg";
            minioHelper.uploadFile(image, filename);
            filenameMap.put("image", minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + filename);
            toolForkInfoEntity.setImage(filename);
        }
        //二维图片
        if (!ObjectUtil.isNull(twoDimensionalModel)) {
            filename = idnr + partno + TWO_DIMENSIONAL_MODEL + ".jpg";
            minioHelper.uploadFile(twoDimensionalModel, filename);
            filenameMap.put("twoDimensionalModel", minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + filename);
            toolForkInfoEntity.setTwoDimensionalModel(filename);
        }
        //三维图片
        if (!ObjectUtil.isNull(threeDimensionalModel)) {
            filename = idnr + partno + THREE_DIMENSIONAL_MODEL + ".stp";
            minioHelper.uploadFile(threeDimensionalModel, filename);
            filenameMap.put("threeDimensionalModel", minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + filename);
            toolForkInfoEntity.setThreeDimensionalModel(filename);
        }
        //三维图片stl
        if (!ObjectUtil.isNull(threeDimensionalModelStl)) {
            filename = idnr + partno + THREE_DIMENSIONAL_MODEL + ".stl";
            minioHelper.uploadFile(threeDimensionalModelStl, filename);
            filenameMap.put("threeDimensionalModelStl", minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + filename);
            toolForkInfoEntity.setThreeDimensionalModelStl(filename);
        }
        if (ObjectUtil.isNotNull(toolForkInfoEntity.getId())) {
            //表中存在记录则修改实体类图片地址
            toolForkInfoMapper.updateById(toolForkInfoEntity);
        }
        return filenameMap;
    }

    public void removeFile(String fileUrl) {
        if (!ObjectUtil.isNull(fileUrl)) {
            String[] split = fileUrl.split("/");
            String fileName = split[split.length - 1];
//            QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
//            if(fileName.contains(IMAGE)){
//                wrapper.eq("image" , fileName);
//            }else if(fileName.contains(TWO_DIMENSIONAL_MODEL)){
//                wrapper.eq("twoDimensionalModel" , fileName);
//            }else if(fileName.contains(THREE_DIMENSIONAL_MODEL)){
//                wrapper.eq("threeDimensionalModel" , fileName);
//            }
//            ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
//            if(fileName.contains(IMAGE)){
//                toolForkInfoEntity.setImage("");
//            }else if(fileName.contains(TWO_DIMENSIONAL_MODEL)){
//                toolForkInfoEntity.setTwoDimensionalModel("");
//            }else if(fileName.contains(THREE_DIMENSIONAL_MODEL)){
//                toolForkInfoEntity.setThreeDimensionalModel("");
//            }

            RemoveFileContext removeFileContext = new RemoveFileContext();
            removeFileContext.removeFileByStrategy(fileName , 2);
            //minioHelper.removeFile(fileName);
        }
    }


    public String downloadFile(String fileUrl) {
        if (ObjectUtil.isNotNull(fileUrl)) {
            String[] split = fileUrl.split("/");
            String filename = split[split.length - 1];

//            DownFileContext downFileContext = new DownFileContext();
//            downFileContext.downloadFileByStrategy(response , filename , 2);
            //minioHelper.downloadGetObjectStream(response, filename);
            minioHelper.downloadGetObjectUrlReload(filename);
            return minioHelper.downloadGetObjectUrlReload(filename);
        }
        return "";
    }


    public Object queryToolForkIndexParams(Integer index) {
        String params = toolForkRespository.queryParamsById(index);
        List<Map<String, Object>> paramsList = new ArrayList<>();
        if (ObjectUtil.isNotNull(params)) {
            String[] split = params.split(",");
            for (String s : split) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("name", s);
                paramMap.put("value", "");
                paramsList.add(paramMap);
            }
        }
        return paramsList;
    }

    public Object getToolIndex() {
        Map<String, Object> retMap = new HashMap<>();
        List<Map<String, Object>> toolForkCycleList = new ArrayList<>();
        List<Map<String, Object>> toolForkBarList = new ArrayList<>();
        List<Map<String, Object>> assemblyToolBarList = new ArrayList<>();
        //在线刀具统计环形图
        toolTypeFirstMap.forEach((key, value) -> {
            Map<String, Object> toolForkCycleMap = new HashMap<>();
            toolForkCycleMap.put("name", key);
            Integer number = toolForkRespository.countByType(value);
            toolForkCycleMap.put("number", number);
            toolForkCycleList.add(toolForkCycleMap);
        });
        retMap.put("toolForkCycleList", toolForkCycleList);
        //在线刀具统计柱状图
        toolTypeSecMap.forEach((key, value) -> {
            Map<String, Object> toolForkBarMap = new HashMap<>();
            toolForkBarMap.put("name", key);
            Integer number = toolForkRespository.countByType(value);
            toolForkBarMap.put("number", number);
            toolForkBarList.add(toolForkBarMap);
        });
        retMap.put("toolForkBarList", toolForkBarList);
        //我的总成柱状图
        List<Map<String, Long>> assemblyToolTypeMapList = assemblyToolRespository.selectAssemblyBarMap();
        assemblyToolTypeMapList.forEach(stringLongMap -> {
            Map<String, Object> assemblyToolBarMap = new HashMap<>();
            assemblyToolBarMap.put("name", stringLongMap.get("type"));
            assemblyToolBarMap.put("number", stringLongMap.get("number"));
            assemblyToolBarList.add(assemblyToolBarMap);
        });
        retMap.put("assemblyToolBarList", assemblyToolBarList);
        return retMap;
    }

    public Object importToolInfoData(String params) {
        List<Map> paramsMapList = JSONArray.parseArray(params, Map.class);
        paramsMapList.forEach(map -> {
            ToolForkInfoEntity toolForkInfoEntity = new ToolForkInfoEntity();
            //获取类型
            QueryWrapper<TypeItemEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("type_name", map.get("type"));
            TypeItemEntity typeItemEntity = typeItemMapper.selectOne(wrapper);
            toolForkInfoEntity.setType(typeItemEntity.getType());
            String paramKey = typeItemEntity.getParams();
            if (StringUtil.isNotEmpty(paramKey)) {
                String[] split = paramKey.split(",");
                Arrays.stream(split).forEach(s -> {
                    //map.get(s)
                });
            }
        });
        return null;
    }

    public PageResult<ToolForkInfoEntity> queryToolForkInfo(QueryToolForkInfoReq queryToolForkInfoReq) {
        List<ToolForkInfoEntity> pageList = new ArrayList<>();
        List<ToolForkInfoEntity> resultList = new ArrayList<>();
        if (ObjectUtil.isNull(queryToolForkInfoReq.getIic())
                && ObjectUtil.isNull(queryToolForkInfoReq.getCcms())
                && ObjectUtil.isNull(queryToolForkInfoReq.getCcws())) {
            return query(queryToolForkInfoReq);
        }
        List<ToolForkInfoEntity> toolForkInfoEntities = queryReload(queryToolForkInfoReq);
        //List<ToolForkInfoEntity> toolForkInfoEntities = queryReload(queryToolForkInfoReq);
        if (StringUtil.isNotEmpty(queryToolForkInfoReq.getIic()) && StringUtils.isBlank(queryToolForkInfoReq.getWiperCode())) {
            //匹配iic 标志位为1
            resultList = matchIIc(toolForkInfoEntities, queryToolForkInfoReq.getIic());
        }
        if (StringUtil.isNotEmpty(queryToolForkInfoReq.getIic()) && StringUtil.isNotEmpty(queryToolForkInfoReq.getWiperCode())) {
            //匹配iic 标志位为1
            resultList = matchIIc(toolForkInfoEntities, queryToolForkInfoReq.getIic());
            //过滤出wiperCode为1的数据
            if(CollectionUtil.isNotEmpty(resultList)){
                resultList  = resultList.stream().filter(toolForkInfoEntity -> {
                    if(StringUtils.isNotBlank(toolForkInfoEntity.getParameters())){
                        List<ToolParam> toolParams = JSONArray.parseArray(toolForkInfoEntity.getParameters(), ToolParam.class);
                        for (ToolParam toolParam : toolParams) {
                            if(toolParam.getNameEn().equals("WIPER_CODE") && toolParam.getValue().equals("1")){
                                return true;
                            }
                        }
                    }
                    return false;
                }).collect(Collectors.toList());
            }
        }
        if (StringUtil.isNotEmpty(queryToolForkInfoReq.getCcws())) {
            //匹配ccms 标志位2
            resultList = matchCCWS(queryToolForkInfoReq, queryToolForkInfoReq.getCcws());
        }
        if (StringUtil.isNotEmpty(queryToolForkInfoReq.getCcms())) {
            //匹配ccws 标志位2
            resultList = matchCCMS(queryToolForkInfoReq, queryToolForkInfoReq.getCcms());
        }
        //过滤resultList中缺少originalParams的数据,避免自建数据由于缺少模型地址导致无法通过模型获取接口获取总成模型
        if(CollectionUtil.isNotEmpty(resultList)){
            resultList = resultList.stream().filter(toolForkInfoEntity -> StringUtils.isNotBlank(toolForkInfoEntity.getOriginalParams())).collect(Collectors.toList());
        }
        pageList = CommonUtil.pageList(resultList, queryToolForkInfoReq.getPageNum(), queryToolForkInfoReq.getPageSize());
        List<String> partnos = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(pageList)){
            partnos = pageList.stream().map(ToolForkInfoEntity::getPartno).collect(Collectors.toList());
        }
        List<ToolForkInfoCountVo> countVos = toolPartRespository.selectCountByPartnos(partnos);
        countVos = countVos.stream().filter(toolForkInfoCountVo -> ObjectUtil.isNotNull(toolForkInfoCountVo.getPartno()) && ObjectUtil.isNotNull(toolForkInfoCountVo.getNumber())).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(countVos)){
            Map<String , Integer> partnoCountMap = countVos
                    .stream()
                    .collect(Collectors.toMap(ToolForkInfoCountVo::getPartno , ToolForkInfoCountVo::getNumber));
            queryStock(pageList , partnoCountMap);
        }
        return new PageResult<>(pageList, (long) resultList.size());
    }

    private List<ToolForkInfoEntity> matchCCMS(QueryToolForkInfoReq queryToolForkInfoReq, String ccms) {
        if (ccms.length() == 14) {
            //14位ccws匹配14位ccms
            List<String> strings = CommonUtil.ccws14Split1(ccms);
            String match1 = strings.get(0) + strings.get(1) + strings.get(2);
            String match2 = strings.get(0) + "**" + strings.get(2);
            String match3 = strings.get(0) + "$$" + strings.get(2);
            //flag = 0 为ccws匹配14位ccms
            List<ToolForkInfoEntity> list1 = queryCCWSReload1(queryToolForkInfoReq, 3, match1, match2, match3);
            //14位ccws匹配28位ccms
            List<String> splitStrings = CommonUtil.ccws14Split2(ccms);
            String match4 = strings.get(0) + strings.get(1);
            String match5 = strings.get(0) + "**";
            String match6 = strings.get(0) + "$$";
            Integer matchNumber = Integer.parseInt(splitStrings.get(2));
            List<ToolForkInfoEntity> list2 = queryCCWSReload1(queryToolForkInfoReq, 3, match4, match5, match6);
            //处理倍率与范围
            if (CollectionUtil.isNotEmpty(list2)) {
                list2 = list2.stream().filter(toolForkInfoEntity -> {
                    if (toolForkInfoEntity.getCcws().length() == 28) {
                        List<String> filterList = CommonUtil.ccws28Split(toolForkInfoEntity.getCcws());
                        return Integer.parseInt(filterList.get(2)) <= matchNumber && Integer.parseInt(filterList
                                .get(3)) >= matchNumber;
                    }
                    return false;
                }).collect(Collectors.toList());
            }
            //整合list1与list2
            List<ToolForkInfoEntity> concatList = Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(concatList)) {
                concatList = concatList.stream().filter(toolForkInfoEntity -> ObjectUtil.isNotNull(toolForkInfoEntity.getPartno())).distinct().collect(Collectors.toList());
            }
            return concatList;
        }
        if (ccms.length() == 28) {
            List<String> strings = CommonUtil.ccws28Split(ccms);
            String match1 = strings.get(0) + strings.get(1);
            String match2 = strings.get(0) + "**";
            String match3 = strings.get(0) + "$$";
            List<ToolForkInfoEntity> list = queryCCWSReload1(queryToolForkInfoReq, 4, match1, match2, match3);
            //对list进行范围匹配
            if (CollectionUtil.isNotEmpty(list)) {
                return list.stream().filter(toolForkInfoEntity -> {
                    if (toolForkInfoEntity.getCcws().length() == 14) {
                        List<String> filterList = CommonUtil.ccws14Split2(toolForkInfoEntity.getCcws());
                        return Integer.parseInt(strings.get(2)) <= Integer.parseInt(filterList.get(2))
                                && Integer.parseInt(strings.get(3)) >= Integer.parseInt(filterList.get(2));
                    }
                    return false;
                }).collect(Collectors.toList());
            }
        }
        return new ArrayList<>();
    }

    private List<ToolForkInfoEntity> matchCCWS(QueryToolForkInfoReq queryToolForkInfoReq, String ccws) {
        if (ccws.length() == 14) {
            //14位ccws匹配14位ccms
            List<String> strings = CommonUtil.ccws14Split1(ccws);
            String match1 = strings.get(0) + strings.get(1) + strings.get(2);
            String match2 = strings.get(0) + "**" + strings.get(2);
            String match3 = strings.get(0) + "$$" + strings.get(2);
            //flag = 0 为ccws匹配14位ccms
            List<ToolForkInfoEntity> list1 = queryCCWSReload1(queryToolForkInfoReq, 1, match1, match2, match3);
            //14位ccws匹配28位ccms
            List<String> splitStrings = CommonUtil.ccws14Split2(ccws);
            String match4 = strings.get(0) + strings.get(1);
            String match5 = strings.get(0) + "**";
            String match6 = strings.get(0) + "$$";
            if (splitStrings.size() == 2) {
                return list1;
            }
            Integer matchNumber = Integer.parseInt(splitStrings.get(2));
            List<ToolForkInfoEntity> list2 = queryCCWSReload1(queryToolForkInfoReq, 1, match4, match5, match6);
            //处理倍率与范围
            if (CollectionUtil.isNotEmpty(list2)) {
                list2 = list2.stream().filter(toolForkInfoEntity -> {
                    if (StringUtil.isNotEmpty(toolForkInfoEntity.getCcms())
                            &&toolForkInfoEntity.getCcms().length() == 28) {
                        List<String> filterList = CommonUtil.ccws28Split(toolForkInfoEntity.getCcms());
//                        return Integer.parseInt(filterList.get(2)) <= matchNumber && Integer.parseInt(filterList
//                                .get(3)) >= matchNumber;
                        return rangeMatch(Arrays.asList(filterList.get(2) , filterList.get(3)) , Arrays.asList(splitStrings.get(2) , splitStrings.get(2)));
                    }
                    return false;
                }).collect(Collectors.toList());
            }
            //整合list1与list2
            List<ToolForkInfoEntity> concatList = Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(concatList)) {
                concatList = concatList.stream().distinct().collect(Collectors.toList());
            }
            return concatList;
        }
        if (ccws.length() == 28) {
            List<String> strings = CommonUtil.ccws28Split(ccws);
            String match1 = strings.get(0) + strings.get(1);
            String match2 = strings.get(0) + "**";
            String match3 = strings.get(0) + "$$";
            List<ToolForkInfoEntity> list = queryCCWSReload1(queryToolForkInfoReq, 2, match1, match2, match3);
            //对list进行范围匹配
            if (CollectionUtil.isNotEmpty(list)) {
                return list.stream().filter(toolForkInfoEntity -> {
                    if (toolForkInfoEntity.getCcms().length() == 14) {
                        List<String> filterList = CommonUtil.ccws14Split2(toolForkInfoEntity.getCcms());
//                        return Integer.parseInt(strings.get(2)) <= Integer.parseInt(filterList.get(2))
//                                && Integer.parseInt(strings.get(3)) >= Integer.parseInt(filterList.get(2));
                        return rangeMatch(Arrays.asList(strings.get(2) , strings.get(3)) , Arrays.asList(filterList.get(2) , filterList.get(2)));
                    }
                    return false;
                }).collect(Collectors.toList());
            }
        }
        return new ArrayList<>();
    }

    private void queryStock(List<ToolForkInfoEntity> pageList , Map<String , Integer> partnoCountMap) {
        if(CollectionUtil.isEmpty(partnoCountMap)){
            return;
        }
        if (CollectionUtil.isNotEmpty(pageList)) {
            pageList.forEach(toolForkInfoEntity -> {
                toolForkInfoEntity.setSign(ObjectUtil.isNotNull(partnoCountMap.get(toolForkInfoEntity.getPartno()))
                        ? toolPartRespository.selectCountByPartno(toolForkInfoEntity.getPartno())
                        : 0);
            });
        }
    }

    private List<ToolForkInfoEntity> matchIIc(List<ToolForkInfoEntity> toolForkInfoEntities, String value) {
        List<String> strings = CommonUtil.iicStrSplit(value);
        String matchStr = "";
        //生成正则表达式
        if (Objects.equals(strings.get(3), "N")) {
            matchStr = strings.get(0) + ".." + strings.get(2) + "." + strings.get(4) + "....";
        } else {
            matchStr = strings.get(0) + ".." + strings.get(2) + "[" + strings.get(3) + "N" + "]" + strings.get(4) + "....";
        }
        //转义$符号
        matchStr = matchStr.replaceAll("\\$", "\\\\\\$");
        final String match = matchStr;
        //匹配1-10位 13  14  15位
        toolForkInfoEntities = toolForkInfoEntities
                .stream()
                .filter(toolForkInfoEntity -> {
                    if (StringUtil.isNotEmpty(toolForkInfoEntity.getIic())) {
                        return toolForkInfoEntity.getIic().matches(match);
                    }
                    return false;
                }).collect(Collectors.toList());
        //匹配为空 直接return
        if (CollectionUtil.isEmpty(toolForkInfoEntities)) {
            return toolForkInfoEntities;
        }
        //11-12  18-19位进行范围匹配
        if (strings.get(1).contains("$") || strings.get(5).contains("$")) {
            return toolForkInfoEntities;
        }
//        if (Integer.valueOf(strings.get(1)).equals(Integer.valueOf(strings.get(5)))) {
//            //刀片匹配刀具
//            return toolForkInfoEntities
//                    .stream()//过滤11-12 18-19位含$符的
//                    .filter(toolForkInfoEntity -> {
//                        List<String> filterStrings = CommonUtil.iicStrSplit(toolForkInfoEntity.getIic());
//                        if (filterStrings.get(1).contains("$") || filterStrings.get(5).contains("$")) {
//                            return false;
//                        }
//                        return rangeMatch(Arrays.asList(strings.get(1) , strings.get(5)),Arrays.asList(filterStrings.get(1) , filterStrings.get(5)));
//                    }).collect(Collectors.toList());
//        }
        //刀具匹配刀片
        return toolForkInfoEntities
                .stream()//过滤11-12 18-19位含$符的
                .filter(toolForkInfoEntity -> {
                    List<String> filterStrings = CommonUtil.iicStrSplit(toolForkInfoEntity.getIic());
                    if (filterStrings.get(1).contains("$") || filterStrings.get(5).contains("$")) {
                        return true;
                    }
//                    return Integer.parseInt(strings.get(1)) <= Integer.parseInt(filterStrings.get(1))
//                            && Integer.parseInt(strings.get(5)) >= Integer.parseInt(filterStrings.get(1));
                    return rangeMatch(Arrays.asList(strings.get(1) , strings.get(5)),Arrays.asList(filterStrings.get(1) , filterStrings.get(5)));
                }).collect(Collectors.toList());
    }

    private static boolean rangeMatch(List<String> strings, List<String> filterStrings) {
        //区间左值
        int minNum = 0;
        //区间右值
        int maxNum = 0;
        //匹配值
        int value = 0;
        List<Integer> integers1 = strings.stream().map(Integer::valueOf).collect(Collectors.toList());
        List<Integer> integers2 = filterStrings.stream().map(Integer::valueOf).collect(Collectors.toList());
        List<List<Integer>> lists = Arrays.asList(integers1, integers2);
        for (List<Integer> list : lists) {
            if(Objects.equals(list.get(0), list.get(1))){
                //相等为值
                value = list.get(0);
            }else{
                //不等为区间
                maxNum = CollectionUtil.max(list);
                minNum = CollectionUtil.min(list);
            }
        }
        //比较区间是否包含该值
        return value >= minNum && value <= maxNum;
    }


    public Object updateToolPrice(List<ToolForkInfoPriceImport> importData) {
        if(CollectionUtil.isEmpty(importData)){
            return Boolean.FALSE;
        }
        List<ToolForkInfoEntity> updateList = new ArrayList<>();
        importData.forEach(toolForkInfoPriceImport->{
            QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("partno" , toolForkInfoPriceImport.getPartno());
            ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
            if(ObjectUtil.isNotNull(toolForkInfoEntity)){
                toolForkInfoEntity.setPrice(toolForkInfoPriceImport.getPrice());
                updateList.add(toolForkInfoEntity);
            }
        });
        if(CollectionUtil.isNotEmpty(updateList)){
            toolForkInfoMapper.updateBatchById(updateList);
        }
        return Boolean.TRUE;
    }

    public Object uploadFiles(MultipartFile file , String flag) {
//        Context context = new Context();
//        context.uploadByStrategy(flag , file , file.getOriginalFilename());
        minioHelper.uploadFile(file, file.getOriginalFilename());
        return Boolean.TRUE;
    }

    public Object toolInfoManagement(ToolInfoManagementReq toolInfoManagementReq) {
        QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("partno");
        wrapper.ne("partno" ,"");
        if(StringUtils.isNotEmpty(toolInfoManagementReq.getPartno())){
            wrapper.like("partno" , toolInfoManagementReq.getPartno());
        }
        if(StringUtils.isNotEmpty(toolInfoManagementReq.getIdnr())){
            wrapper.like("idnr" , toolInfoManagementReq.getIdnr());
        }
        PageHelper.startPage(toolInfoManagementReq.getPageNum() , toolInfoManagementReq.getPageSize());
        PageInfo<ToolForkInfoEntity> pageInfo = new PageInfo<>(toolForkInfoMapper.selectList(wrapper));
        if(CollectionUtil.isNotEmpty(pageInfo.getList())){
            pageInfo.getList().forEach(toolForkInfoEntity -> {
                List<ToolLifeEntity> toolLifeEntities = toolLifeRepository.selectLifeByPartno(toolForkInfoEntity.getPartno());
                if(CollectionUtil.isNotEmpty(toolLifeEntities)){
                    toolForkInfoEntity.setToolLife(toolLifeEntities.get(0).getLife());
                }
            });
        }
        return new PageResult<>(pageInfo.getList() , pageInfo.getTotal());
    }

    @Transactional
    public Object editToolInfoManagement(EditToolInfoManagementReq editToolInfoManagementReq) {
        toolForkRespository.editPriceByPartno(editToolInfoManagementReq.getPartno() , editToolInfoManagementReq.getPrice());
        //查询是否有这条记录 有则修改 没有新增
        QueryWrapper<ToolLifeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("classify" , editToolInfoManagementReq.getPartno());
        ToolLifeEntity toolLifeEntity = toolLifeMapper.selectOne(wrapper);
        if(ObjectUtil.isNotNull(toolLifeEntity)){
            toolLifeRepository.editLifeByPartno(editToolInfoManagementReq.getPartno() , editToolInfoManagementReq.getLife());
            return Boolean.TRUE;
        }
        ToolLifeEntity insertEntity = new ToolLifeEntity();
        insertEntity.setClassify(editToolInfoManagementReq.getPartno());
        insertEntity.setLife(editToolInfoManagementReq.getLife());
        insertEntity.setTypeFlag(0);
        toolLifeMapper.insert(insertEntity);
        return Boolean.TRUE;
    }

    public Object selectById(Integer id) {
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectById(id);
        toolForkInfoEntity.setParameters("");
        return toolForkInfoEntity;
    }

    public Object editToolLife() {
        List<ToolForkInfoEntity> toolForkInfoEntities = toolForkInfoMapper.selectList(new QueryWrapper<>());
        List<ToolLifeEntity> addToolLifeEntities = new ArrayList<>();
        List<ToolLifeEntity> updateToolLifeEntities = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(toolForkInfoEntities)){
            //过滤出丝锥
            List<ToolForkInfoEntity> filterList = toolForkInfoEntities.stream().filter(toolForkInfoEntity ->
                    ObjectUtil.isNotNull(toolForkInfoEntity.getType()) && toolForkInfoEntity.getType().startsWith("A001B001C003D002E001")
            ).collect(Collectors.toList());
            //将丝锥根据规则配置寿命
            List<ToolForkInfoEntity> collect = filterList.stream().filter(toolForkInfoEntity -> {
                if (ObjectUtil.isNotNull(toolForkInfoEntity.getIdnr())) {
                    String idnr = toolForkInfoEntity.getIdnr();
                    if (idnr.contains("M2.5") || idnr.contains("M3") || idnr.contains("M3.5") || idnr.contains("M4") || idnr.contains("M5") || idnr.contains("M6")) {
                        return true;
                    }
                }
                return false;
            }).collect(Collectors.toList());
            QueryWrapper<ToolLifeEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("type_flag" , 0);
            List<ToolLifeEntity> toolLifeEntities = toolLifeMapper.selectList(wrapper);
            List<String> existParnos = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(toolLifeEntities)){
                existParnos = toolLifeEntities
                        .stream()
                        .map(ToolLifeEntity::getClassify)
                        .collect(Collectors.toList());
            }
            for (ToolForkInfoEntity toolForkInfoEntity : collect) {
                BigDecimal life = new BigDecimal("0");
                if(toolForkInfoEntity.getIdnr().contains("M2.5")){
                    life = new BigDecimal("40");
                }else if(toolForkInfoEntity.getIdnr().contains("M3")){
                    life = new BigDecimal("30");
                }else if(toolForkInfoEntity.getIdnr().contains("M3.5")){
                    life = new BigDecimal("30");
                }else if(toolForkInfoEntity.getIdnr().contains("M4")){
                    life = new BigDecimal("40");
                }else if(toolForkInfoEntity.getIdnr().contains("M5")){
                    life = new BigDecimal("30");
                }else if(toolForkInfoEntity.getIdnr().contains("M6")){
                    life = new BigDecimal("30");
                }
                if(StringUtils.isNotBlank(toolForkInfoEntity.getIdnr()) && CollectionUtil.isNotEmpty(existParnos) && !existParnos.contains(toolForkInfoEntity.getPartno())){
                    //修改
                    for (ToolLifeEntity toolLifeEntity : toolLifeEntities) {
                        if(toolLifeEntity.getClassify().equals(toolForkInfoEntity.getPartno())){
                            toolLifeEntity.setLife(life);
                            updateToolLifeEntities.add(toolLifeEntity);
                        }
                    }
                }else{
                    //新增
                    ToolLifeEntity toolLifeEntity = new ToolLifeEntity();
                    toolLifeEntity.setTypeFlag(0);
                    toolLifeEntity.setClassify(toolForkInfoEntity.getPartno());
                    toolLifeEntity.setType(toolForkInfoEntity.getType());
                    toolLifeEntity.setLife(life);
                    addToolLifeEntities.add(toolLifeEntity);
                }
            }
        }
        if(CollectionUtil.isNotEmpty(updateToolLifeEntities)){
            toolLifeMapper.updateBatchById(updateToolLifeEntities);
        }
        if(CollectionUtil.isNotEmpty(addToolLifeEntities)){
            toolLifeMapper.insertBatchSomeColumn(addToolLifeEntities);
        }
        return null;
    }

    public Object editToolLifeReload() {
        List<ToolConnectEntity> toolConnectEntities = toolConnectMapper.selectList(new QueryWrapper<>());
        List<ToolLifeEntity> insertList = new ArrayList<>();
        List<String> existPartnos = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(toolConnectEntities)){
            existPartnos = toolConnectEntities
                    .stream()
                    .map(ToolConnectEntity::getPartno)
                    .collect(Collectors.toList());
        }
        QueryWrapper<ToolLifeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("type_flag" , 0);
        List<ToolLifeEntity> toolLifeEntities = toolLifeMapper.selectList(wrapper);
        List<String> partnos = toolLifeEntities
                .stream()
                .map(ToolLifeEntity::getClassify)
                .collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(existPartnos)){
            for (String existPartno : existPartnos) {
                if(!partnos.contains(existPartno)){
                    QueryWrapper<ToolForkInfoEntity> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("partno" , existPartno);
                    ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper1);
                    //新增
                    if(ObjectUtil.isNotNull(toolForkInfoEntity)){
                        ToolLifeEntity toolLifeEntity = new ToolLifeEntity();
                        toolLifeEntity.setTypeFlag(0);
                        toolLifeEntity.setClassify(toolForkInfoEntity.getPartno());
                        toolLifeEntity.setType(toolForkInfoEntity.getType());
                        toolLifeEntity.setLife(new BigDecimal(60.0));
                        insertList.add(toolLifeEntity);
                    }
                }
            }
        }
        if(CollectionUtil.isNotEmpty(insertList)){
            toolLifeMapper.insertBatchSomeColumn(insertList);
        }
        return null;
    }

    public Object editToolInfoManagementReload(EditToolInfoManagementReq editToolInfoManagementReq) {
        //查询是否有这条记录 有则修改 没有新增
        QueryWrapper<ToolLifeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("classify" , editToolInfoManagementReq.getPartno());
        wrapper.eq("classify" , 0);
        ToolLifeEntity toolLifeEntity = toolLifeMapper.selectOne(wrapper);
        if(ObjectUtil.isNotNull(toolLifeEntity)){
            toolLifeRepository.editLifeByPartno(editToolInfoManagementReq.getPartno() , editToolInfoManagementReq.getLife());
            return Boolean.TRUE;
        }
        ToolLifeEntity insertEntity = new ToolLifeEntity();
        insertEntity.setClassify(editToolInfoManagementReq.getPartno());
        insertEntity.setLife(editToolInfoManagementReq.getLife());
        insertEntity.setTypeFlag(0);
        toolLifeMapper.insert(insertEntity);
        return Boolean.TRUE;
    }

    public Object changeToolForkIno() {
        List<ToolForkInfoEntity> updateList = new ArrayList<>();
        List<ToolForkInfoEntity> toolForkInfoEntities = toolForkInfoMapper.selectList(new QueryWrapper<>());
        toolForkInfoEntities = toolForkInfoEntities.stream().filter(toolForkInfoEntity -> StringUtils.isBlank(toolForkInfoEntity.getOriginalParams())).collect(Collectors.toList());
        for (ToolForkInfoEntity toolForkInfoEntity : toolForkInfoEntities) {
            Map<String , Object> paramMap = new HashMap<>();
            if(StringUtils.isNotBlank(toolForkInfoEntity.getParameters())){
                List<ToolParamReloadVo> toolParams = JSONArray.parseArray(toolForkInfoEntity.getParameters(), ToolParamReloadVo.class);
                if(CollectionUtil.isNotEmpty(toolParams)){
                    for (ToolParamReloadVo toolParamReloadVo : toolParams) {
                        paramMap.put(toolParamReloadVo.getNameEn() , toolParamReloadVo.getValue());
                    }
                }
                toolForkInfoEntity.setOriginalParams(JSONObject.toJSONString(paramMap));
                updateList.add(toolForkInfoEntity);
            }
        }
        if(CollectionUtil.isNotEmpty(updateList)){
            List<List<ToolForkInfoEntity>> lists = CommonUtil.groupList(updateList);
            for (List<ToolForkInfoEntity> list : lists) {
                toolForkInfoMapper.updateBatchById(list);
            }
        }
        return Boolean.TRUE;
    }
}
